// pages/me/manageDealer/manageDealer.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dealerInfo:{
            city:'',
            province:'',
            district:''
        },
        userAgreement: true,
        editDealer: false,
        modalName:  null, // 
        orderInfo:{
            orderNo:'',
            payInfo:{}
        },
        showType:'',
        dealerId:null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        if(options.type){
            this.setData({
                'showType': options.type
            })
        }
        if(options.id){
            this.setData({
                dealerId: options.id
            })
        }
        this.InitUserStatus();
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        let userInfo = app.globalData.userInfo;
        // 这里再验证一遍权限。
        if(this.data.dealerId != null){
            this.loadDealerInfo();
        }else{
            if (userInfo.roleList.indexOf('manageDealer') == -1) {
                app.showNoAuthOrNoGrant('您无权操作查看此页面');
                return;
            }else{
                this.loadDealerInfo();
            }
        }
    },
    loadDealerInfo(){
        app.sHttp.dealerInfo(this.data.dealerId?{dealerId:this.data.dealerId}:{}).then(res =>{
            if(res.result.city == '市辖区'){
              res.result.city = res.result.province;
            }
            res.result.region = [res.result.province, res.result.city , res.result.district];
            res.result.dealerPicLists = [];
            res.result.dealerPicList.forEach(item =>{
                res.result.dealerPicLists.push(item.picUrl);
            });
            // 判断认证时间。
            if(undefined == res.result.authExpiryTime || null == res.result.authExpiryTime || '' == res.result.authExpiryTime){
                res.result.authExpiryStatus = 0;
            }else{
                let howMinute = (((Date.parse(new Date())) - res.result.authExpiryTime) / 1000) / 60;
                if(howMinute>=0){
                    res.result.authExpiryStatus = 0;
                }else{
                    res.result.authExpiryStatus = 1;
                }
            }
            if(undefined == res.result.goldMedalExpiryTime || null == res.result.goldMedalExpiryTime || '' == res.result.goldMedalExpiryTime){
                res.result.goldMedalExpiryStatus = 0;
            }else{
                let howMinute = (((Date.parse(new Date())) - res.result.goldMedalExpiryTime) / 1000) / 60;
                if(howMinute>=0){
                    res.result.goldMedalExpiryStatus = 0;
                }else{
                    res.result.goldMedalExpiryStatus = 1;
                }
            }
            app.globalData.dealerInfo = res.result;
            this.setData({
                'dealerInfo': res.result
            });
            let self = this;
            setTimeout(() => {
                if(self.data.dealerId){
                    self.setData({
                        editDealer: true
                    })
                }
                if(self.data.showType == 'authExpiryStatus'){
                    self.setData({
                        'modalName': 'authExpiry',
                        'showType':''
                    })
                }else if(self.data.showType == 'goldMedalExpiryStatus'){
                    self.setData({
                        'modalName': 'goldMedalExpiry',
                        'showType':''
                    })
                }else if(self.data.showType == 'isTransactionGuarantee'){
                    self.setData({
                        'modalName': 'isTransactionGuarantee',
                        'showType':''
                    })
                }
            }, 200);
        },err=>{
          app.error(err.msg);
        })
    },
    switchEditDealer(){
        let editDealer = !this.data.editDealer;
        this.setData({
            'editDealer': editDealer
        })
    },
    submitForm(e){
        // 查找公司资料对象。
        let self = this;
        // 先修改基本信息。
        // 组装参数。
        let dearlerInfo = e.detail.value;
        dearlerInfo.province = dearlerInfo.region[0];
        dearlerInfo.city = dearlerInfo.region[1];
        dearlerInfo.district = dearlerInfo.region[2];
        delete dearlerInfo.region;
        let chooseDealerLogo = this.selectComponent('#chooseDealerLogo');
        chooseDealerLogo.uploadFiles('dealerLogo',0,false).then(res=>{
            dearlerInfo.logoUrl = res[0].originalUrl;
            if(self.validForm(dearlerInfo)){
                let _this = self;
                // 提交修改.
                if(self.data.dealerId){
                    dearlerInfo['dealerId'] = self.data.dealerId
                }
                app.sHttp.dealerModifyBaseInfo(dearlerInfo).then(res =>{
                    // 提交公司图片资料。
                    let chooseDealerPicList = _this.selectComponent('#chooseDealerPicList');
                    let that = _this;
                    chooseDealerPicList.uploadFiles('dealerData',0,true).then(res=>{
                        let dealerPicList = [];
                        res.forEach(element => {
                            dealerPicList.push({picUrl: element.originalUrl});
                        });
                        // 请求修改。
                        let pdasw = {'dealerPicList': dealerPicList};
                        if(that.data.dealerId){
                            pdasw['dealerId'] = that.data.dealerId
                        }
                        app.sHttp.dealerModifyPicList(pdasw).then(res =>{
                            app.success('修改完成');
                            if(that.data.dealerId){
                                that.BackPage();
                                return;
                            }
                            // 关闭修改状态。重新请求公司信息。
                            that.switchEditDealer();
                            that.loadDealerInfo();
                        },err=>{
                           app.error(err.msg||err);
                        })
                    },err=>{
                     app.error(err.msg||err);
                    });
                },err =>{
                    app.error(err.msg);
                })
            }
        },err=>{
         app.error(err.msg||err);
        });

    }, 
  BackPage() {
    var that = this;
    wx.navigateBack({
        delta: 1,
        fail: function () {
            that.toHome();
        }
    });
  },
  toHome() {
    wx.reLaunch({
        url: '/pages/home/home',
    })
  },
    bindRegionChange: function (e) {
        this.setData({
          'dealerInfo.region': e.detail.value
        })
    },
    validForm(data){
        if(undefined == data.contactName || '' == data.contactName || null == data.contactName){
            app.alert('请输入有效的联系人');
            return false;
        }
        if(undefined == data.contactMobile || '' == data.contactMobile || null == data.contactMobile){
            app.alert('请输入有效的手机号码');
            return false;
        }
        if('' == data.city || '' == data.province || '' == data.district || '' == data.detailAddress){
            app.alert('请输入有效的地址信息');
            return false;
        }
        return true
    },
    showModal(e) {
        if(this.data.dealerId){
            app.alert('无法代缴认证')
            return;
        }
        let status = e.currentTarget.dataset.status;
        if (1 == status) {
            app.alert('您已开通当前认证哦~');
            return;
        }
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
      this.setData({
        modalName: null,
        orderInfo:{
            orderNo:'',
            payInfo:{}
        }
      })
    },
    useUserAgreement(){
      this.setData({
        userAgreement: !this.data.userAgreement
      })
    },
    toDoPay(){
        let orderType = null;
        switch (this.data.modalName) {
            case 'authExpiry':
                orderType = 1;
                break;
            case 'goldMedalExpiry':
                orderType = 2;
                break;
            case 'isTransactionGuarantee':
                orderType = 3;
                break;
        };
        if (null == orderType) {
            app.error('未知订单类型');
            return;
        }
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.sHttp.dealerOrderCreate(orderType).then(res =>{
                let self = this;
                this.setData({
                    'orderInfo.orderNo': res.result.orderNo,
                    'orderInfo.payInfo': res.result.payInfo
                }, () => {
                    self.tuneUpPay();
                });
            },err=>{
              app.error(err.msg);
            })
        }else{
            this.tuneUpPay();
        }
    },
    tuneUpPay(){
        // 从Data里面拿参数
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.alert('支付参数不完整');
            return;
        };
        // 吊起支付。
        let self = this;
        wx.requestPayment({
            timeStamp: orderInfo.payInfo.timeStamp,
            nonceStr: orderInfo.payInfo.nonceStr,
            package: orderInfo.payInfo.package,
            signType: orderInfo.payInfo.signType,
            paySign: orderInfo.payInfo.paySign,
            success (res) {
                // 查询订单完成信息。
                let _this = self;
                app.showLoading('查询订单状态');
                setTimeout(() => {
                    wx.hideLoading();
                    _this.dealerOrderPayResult();
                }, 5000);
            },
            fail (res) {
                app.alert('您已取消支付，可点击立即支付重新支付');
            }
          })
    },
    dealerOrderPayResult(){
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo) {
            app.alert('支付参数不完整');
            return;
        };
        app.sHttp.dealerOrderPayResult(orderInfo.orderNo).then(res =>{
            let orderStatus = res.orderStatus;
            if (0 == orderStatus) {
                this.wxShowModal('查询结果','请等待几分钟后重新进入查看是否开通成功，如长时间未显示开通状态，请联系客服处理');
                return;
            }
            if (1 == orderStatus) {
                this.wxShowModal('支付成功(待审核)','您已支付成功，正在审核中，请耐心等待，如长时间未显示开通状态，请联系客服处理');
                return;
            }
            if (2 == orderStatus) {
                this.wxShowModal('开通成功','已为您开通相关认证');
                return;
            }
            if (3 == orderStatus) {
                this.wxShowModal('审核未通过','您当前开通请求审核未通过，请联系客服处理');
                return;
            }
        },err=>{
          app.error(err.msg);
        })
    },
    wxShowModal(title,content){
        let self = this;
        wx.showModal({
            title: title,
            content: content,
            confirmText: '我知道了',
            showCancel: false,
            success(res) {
                self.hideModal();
                self.loadDealerInfo();
            }
          })
    },
    jumpToUserAgreement(){
      this.hideModal();
      wx.navigateTo({
        url: '/pages/publicPage/userAgreement/userAgreement',
      })
    },
})